import json

import os
import shutil

import pymysql

MYSQL_HOST = 'bdm248315507.my3w.com'
MYSQL_USER = 'bdm248315507'
MYSQL_PASS = 'gaohui4850074'
MYSQL_DB = 'bdm248315507_db'

db_config = {
    'host': MYSQL_HOST,
    'port': 3306,
    'user': MYSQL_USER,
    'password': MYSQL_PASS,
    'db': MYSQL_DB,
    'charset': 'utf8',
    'cursorclass': pymysql.cursors.DictCursor,
    'use_unicode': True,
}
COLORS = ['粉色', '红色', '黑色', '灰色', '绿色', '蓝色', '棕色', '白色', '橙色', '紫色', '裸肤', '藏青']
DATASETS_COLORS = 'E:/cdn/datasets/color'
CDN_PATH = 'E:/cdn'
# CDN_PATH1 = 'D:/cdn1'
conn = pymysql.connect(**db_config)
with conn.cursor() as cur:
    sql = "select * from t_product where catalogID=93 AND id >10642"  # and crawl_from = 'jd'
    cur.execute(sql)
    results = cur.fetchall()
    err_num = 0
    for result in results:
        id = result['id']
        try:
            attrs = eval(result['description'])
            for key in attrs.keys():
                if key.startswith('颜色'):
                    if attrs.get(key)[0:2] in COLORS:
                        print(id, key, attrs.get(key))
                        color_path = os.path.join(DATASETS_COLORS,attrs.get(key)[0:2])
                        print(color_path)
                        if not os.path.exists(color_path):
                            os.makedirs(color_path)
                        #get cover picture
                        cover_file = os.path.join(CDN_PATH,result['picture'])
                        file_name = result['picture'].split('/')[-1]
                        new_cover_file = os.path.join(color_path,file_name)
                        # if not os.path.exists(cover_file):
                        #     cover_file = os.path.join(CDN_PATH1,result['picture'])
                        if os.path.exists(cover_file):
                            shutil.move(cover_file,new_cover_file)

                        #get thumb files
                        # thumbs = result['images'].split(',')
                        # for thumb in thumbs:
                        #     thumb_file = os.path.join(CDN_PATH,thumb)
                        #     file_name = thumb.split('/')[-1]
                        #     new_thumb_file = os.path.join(color_path,file_name)
                        #     if not os.path.exists(thumb_file):
                        #         thumb_file = os.path.join(CDN_PATH1,thumb)
                        #     if os.path.exists(thumb_file):
                        #         shutil.copyfile(thumb_file,new_thumb_file)
        except:
            err_num += 1
            continue
    for sub_dir, dirs, files in os.walk(CDN_PATH):
        if len(dirs)==0 and len(files)==0:
            shutil.move(sub_dir,'E:/temp/')


